package com.zz.framework.core.utils

import com.zz.framework.core.ext.getInt


/**
 * Copyright © 2020 zanezhao All rights reserved.
 * Created by zanezhao on 2020-02-22 15:41.
 * @author: zanezhao 1820022519@qq.com
 * @version: V1.0
 */
object VersionUtils {
    fun versionShouldUpdate(newVersion: String?,oldVersion: String?): Boolean {
        return compareVersion(newVersion,oldVersion)>0
    }
    /**
     * 比较版本名称大小 前比后：大于返回正数， 相等返回0， 小于返回负数
     * @param newVersion
     * @param oldVersion
     * @return version1 < version2 -1 </br>  version1 > version2 1
     */
    fun compareVersion(newVersion: String?, oldVersion: String?): Int {
        var newVersion: String? = newVersion
        var oldVersion: String? = oldVersion
        if (newVersion == null || oldVersion == null) {
            return 0
        }
        newVersion = newVersion.trim().toLowerCase()
        oldVersion = oldVersion.trim().toLowerCase()
        newVersion = newVersion.replace("v", "")
        newVersion = newVersion.replace("_beta", "")
        oldVersion = oldVersion.replace("v", "")
        oldVersion = oldVersion.replace("_beta", "")
        val versionArray1 = newVersion.split("\\.".toRegex()).toTypedArray() // 注意此处为特殊字符，需要转义
        val versionArray2 = oldVersion.split("\\.".toRegex()).toTypedArray() // 注意此处为特殊字符，需要转义
        val maxSizeArray = if (versionArray1.size>versionArray2.size){
            versionArray1
        }else{
            versionArray2
        }
        for (i in maxSizeArray.indices) {
            var sum = versionArray1.getOrNull(i).getInt() - versionArray2.getOrNull(i).getInt()
            if (sum > 0) {
                return 1
            } else if (sum < 0) {
                return -1
            }
        }
        return 0
    }

    @JvmStatic
    fun main(args: Array<String>) {
        println(compareVersion("2.1.10", "2.1.9"))
        println(versionShouldUpdate("2.1.10", "2.1.9"))
    }
}